import { defineStore } from 'pinia';
import { store } from '/@/store';
import { basicRoutes } from '/@/router/basicRoutes';
import Layout from '/@/components/Layout/Index.vue';
import ParentView from '/@/components/ParentView/index.vue';
import { buildMenusApi } from '/@/api/menu';
import { router } from '/@/router';

const modules = import.meta.glob('../../views/**/*.vue');

export const usePermissionStore = defineStore({
  id: 'app-permission',
  state: () => ({
    routers: basicRoutes,
    addRouters: [],
    sidebarRouters: [] as any,
  }),
  getters: {
    getRouters(): any {
      return this.routers;
    },
    getSidebarRouters(): any {
      return this.sidebarRouters;
    },
  },
  actions: {
    GenerateRoutes(asyncRouter) {
      this.addRouters = asyncRouter;
      this.routers = basicRoutes.concat(asyncRouter);
    },
    SetSidebarRouters(sidebarRouter) {
      this.sidebarRouters = basicRoutes.concat(sidebarRouter);
    },
    async LoadMenusAction(next, to) {
      const res = await buildMenusApi();
      const sdata = JSON.parse(JSON.stringify(res));
      const rdata = JSON.parse(JSON.stringify(res));
      const sidebarRoutes = filterAsyncRouter(sdata);
      const rewriteRoutes = filterAsyncRouter(rdata, true);
      rewriteRoutes.push({ path: '/:catchAll(.*)', redirect: '/404', hidden: true });

      this.GenerateRoutes(rewriteRoutes);
      Object.keys(rewriteRoutes).forEach((key: string) => {
        router.addRoute(rewriteRoutes[key]);
      });
      next({ ...to, replace: true });
      this.SetSidebarRouters(sidebarRoutes);
    },
  },
});

export const filterAsyncRouter = (routers, isRewrite = false) => {
  // 遍历后台传来的路由字符串，转换为组件对象
  return routers.filter((router) => {
    if (isRewrite && router.children) {
      router.children = filterChildren(router.children);
    }
    if (router.component) {
      if (router.component === 'Layout') {
        // Layout组件特殊处理
        router.component = Layout;
      } else if (router.component === 'ParentView') {
        router.component = ParentView;
      } else {
        const component = router.component;
        router.component = loadView(component);
      }
    }
    if (router.children && router.children.length) {
      router.children = filterAsyncRouter(router.children, isRewrite);
    }
    return true;
  });
};

function filterChildren(childrenMap) {
  var children: any = [];
  childrenMap.forEach((el) => {
    if (el.children && el.children.length) {
      if (el.component === 'ParentView') {
        el.children.forEach((c) => {
          c.path = el.path + '/' + c.path;
          if (c.children && c.children.length) {
            children = children.concat(filterChildren(c.children));
            return;
          }
          children.push(c);
        });
        return;
      }
    }
    children = children.concat(el);
  });
  return children;
}

export const loadView = (view) => {
  return modules[`../../views/${view}.vue`];
};

// Need to be used outside the setup
export function usePermissionStoreWithOut() {
  return usePermissionStore(store);
}
